<template>
  <!-- 分类参数列表 -->
  <div class="params">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <!-- 级联选择器区域 -->
      <el-form>
        <el-form-item label="选择商品参数：">
          <el-cascader
            expand-trigger="hover"
            v-model="selectedVal"
            :options="goodsCate"
            :props="goodsCateProp"
            clearable
            @change="handleSelectGoodsCate"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- tabs 选项卡切换区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮区域 -->
          <el-row>
            <el-col>
              <el-button type="primary" size="mini" @click="addParams" :disabled="isBtnDisable">添加参数</el-button>
            </el-col>
          </el-row>
          <!-- 动态参数表格区域 -->
          <el-table :data="manyTableData" stripe border>
            <!-- 动态参数展开行表格列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  :disable-transitions="false"
                  closable
                  @close="removeTagById(scope.row, i)"
                >{{item}}</el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="paramsVal"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="addParamsInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" align="center"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParamsById(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态属性按钮区域 -->
          <el-row>
            <el-col>
              <el-button type="primary" size="mini" @click="addParams" :disabled="isBtnDisable">添加属性</el-button>
            </el-col>
          </el-row>
          <!-- 静态属性表格区域 -->
          <el-table :data="onlyTableData" stripe border>
            <!-- 静态属性展开行表格列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  :disable-transitions="false"
                  closable
                  @close="removeTagById(scope.row, i)"
                >{{item}}</el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="paramsVal"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="addParamsInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" align="center"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParamsById(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加  动态参数 / 静态属性 对话框-->
      <el-dialog
        :title="'添加' + text"
        :visible.sync="addDialogVisible"
        @close="handleAddDialogClose"
      >
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item :label="text" prop="attr_name">
            <el-input v-model="addForm.attr_name" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureAddClick">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑参数或属性对话框 -->
      <el-dialog
        :title="'编辑' + text"
        :visible.sync="editDialogVisible"
        @close="handleEditDialogClose"
      >
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item :label="text" prop="attr_name">
            <el-input v-model="editForm.attr_name" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureEditClick">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 激活的面板名称
      activeName: 'many',
      // 级联选择器选中值
      selectedVal: [],
      // 级联选择器绑定的值
      goodsCate: [],
      // 级联选择器需要配置属性
      goodsCateProp: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 动态分类参数列表
      manyTableData: [],
      // 静态分类属性列表
      onlyTableData: [],
      // 添加参数或属性的表单对象
      addForm: {
        attr_name: ''
      },
      // 添加参数或属性的表单验证对象
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数或者属性', trigger: 'blur' }
        ]
      },
      // 控制添加动态参数或者静态属性的对话框的显示和隐藏
      addDialogVisible: false,
      // 控制编辑参数或属性的对话框显示和隐藏
      editDialogVisible: false,
      // 编辑表单对象
      editForm: {},
      // 编辑表单验证对象
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数或者属性', trigger: 'blur' }
        ]
      },
      inputVisible: false,
      // 添加参数输入框双向绑定的值
      paramsVal: ''
    }
  },
  created() {
    this.getGoodsCateList()
  },
  methods: {
    // 获取商品分类数据
    getGoodsCateList() {
      this.$nextTick(async _ => {
        const { data: res } = await this.$axios.get('categories', { type: 3 })
        // 获取商品分类列表数据失败
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品分类失败！！！')
        }
        console.log()
        // 成功
        this.goodsCate = res.data
      })
    },
    // 监听切换面板
    handleClick() {
      // 过滤掉除了三级分类id
      if (this.selectedVal.length !== 3) {
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      this.getparamsData()
    },
    // 监听级联选择器change事件
    handleSelectGoodsCate() {
      // 过滤掉除了三级分类id
      if (this.selectedVal.length !== 3) {
        this.manyTableData = []
        this.onlyTableData = []
        this.selectedVal = []
        return
      }
      this.getparamsData()
    },
    // 获取参数列表数据
    async getparamsData() {
      // 获取参数列表
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      // 获取参数列表失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取列表失败！！！')
      }
      const tagArr = res.data.map(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        // 控制添加参数的输入框显示和隐藏
        item.inputVisible = false
        return item
      })
      // 获取数据成功
      if (this.activeName === 'many') {
        this.manyTableData = tagArr
      } else {
        this.onlyTableData = tagArr
      }
    },
    // 点击按钮添加参数或属性
    addParams() {
      // 显示对话框
      this.addDialogVisible = true
    },
    // 监听 点击确定按钮添加参数或属性
    sureAddClick() {
      // 表单预验证
      this.$refs['addFormRef'].validate(async valid => {
        if (valid) {
          const { data: res } = await this.$axios.post(
            `categories/${this.cateId}/attributes`,
            {
              attr_sel: this.activeName,
              attr_name: this.addForm.attr_name
            }
          )
          // 添加参数失败
          if (res.meta.status !== 201) {
            return this.$message.error('添加参数失败!!!')
          }
          // 添加参数成功
          this.$message({
            type: 'success',
            message: '添加参数成功'
          })
          // 刷新列表数据
          this.getparamsData()
          // 关闭对话框
          this.addDialogVisible = false
        }
      })
    },
    // 监听关闭对话框
    handleAddDialogClose() {
      this.$refs['addFormRef'].resetFields()
      this.addForm = {}
    },
    // 根据id查询参数
    async findParams(attrId) {
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      // 获取失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败!!!')
      }
      this.editForm = res.data
    },
    // 点击按钮编辑参数或属性
    editParams(attrId) {
      // 查询参数
      this.findParams(attrId)
      // 显示对话框
      this.editDialogVisible = true
    },
    // 监听 关闭对话框
    handleEditDialogClose() {
      this.$refs['editFormRef'].resetFields()
      this.editForm = {}
    },
    // 监听 点击确定按钮编辑
    sureEditClick() {
      // 表单预处理
      this.$refs['editFormRef'].validate(async valid => {
        if (valid) {
          const { data: res } = await this.$axios.put(
            `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
            {
              attr_sel: this.activeName,
              attr_name: this.editForm.attr_name
            }
          )
          // 编辑失败
          if (res.meta.status !== 200) {
            return this.$message.error('编辑参数失败!!!')
          }
          // 编辑成功
          this.$message({
            type: 'success',
            message: '编辑参数成功'
          })
          // 刷新数据列表
          this.getparamsData()
          // 隐藏对话框
          this.editDialogVisible = false
        }
      })
    },
    // 点击按钮删除对应的参数
    async removeParamsById(attrId) {
      // 确认用户是否删除该参数
      const confirmResult = await this.MessageBox.confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 用户取消了删除
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // 删除参数
      const { data: res } = await this.$axios.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      // 删除失败
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败！！！')
      }
      // 提示
      this.$message({
        type: 'success',
        message: '删除参数成功'
      })
      // 刷新数据列表
      this.getparamsData()
    },
    // 处理输入框的回车或者失去焦点函数
    handleInputConfirm(row) {
      // 隐藏输入框
      row.inputVisible = false
      if (this.paramsVal === '') {
        return
      }
      // 往attr_vals添加一条数据
      row.attr_vals.push(this.paramsVal)
      // 保存
      this.savaAttrVals(row)
      // 置空
      this.paramsVal = ''
    },
    // 保存attr_vals到数据库中
    async savaAttrVals(row) {
      const { data: res } = await this.$axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_sel: this.activeName,
          attr_name: row.attr_name,
          attr_vals: row.attr_vals.join(',')
        }
      )
      // 添加参数失败
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败!!!')
      }
      // 添加参数成功
      this.$message({
        type: 'success',
        message: '修改参数成功'
      })
    },
    // 监听 删除tags
    async removeTagById(row, i) {
      // 提示用户确定执行删除操作
      const confirmResult = await this.MessageBox.confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 用户取消了删除
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // 点击删除
      row.attr_vals.splice(i, 1)
      // 保存
      this.savaAttrVals(row)
    },
    // 监听添加按钮点击事件
    addParamsInput(row) {
      // 显示输入框
      row.inputVisible = true
    }
  },
  computed: {
    // 如果需要禁用按钮 返回true 否则返回false
    isBtnDisable() {
      if (this.selectedVal.length !== 3) {
        return true
      }
      return false
    },
    // 三级分类id
    cateId() {
      if (this.selectedVal.length === 3) {
        return this.selectedVal[2]
      }
      return null
    },
    // 根据需要返回相应的动态和静态文本
    text() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.params {
  .el-form-item {
    margin: 15px 0 !important;
  }
}
.el-tag {
  margin: 0 10px;
}
</style>
<style lang="less">
.el-cascader-panel {
  height: 200px;
}
</style>
